#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
调试样本编号显示问题
检查数据库中样本编号字段的实际值和显示逻辑
"""

import sys
import os
import logging

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from src.utils.database_pagination_manager import DatabasePaginationManager
from src.core.database_manager import DatabaseManager

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

logger = logging.getLogger(__name__)

def debug_sample_number_data():
    """调试样本编号数据"""
    logger.info("=== 调试样本编号显示问题 ===")
    
    # 创建数据库管理器
    db_manager = DatabaseManager()
    db_path = db_manager.db_path
    
    import sqlite3
    
    with sqlite3.connect(db_path) as conn:
        cursor = conn.cursor()
        
        # 检查样本编号字段的数据
        logger.info("检查样本编号字段数据...")
        cursor.execute("""
            SELECT id, sample_no, sample_uid, patient_name, receive_time 
            FROM lis_samples 
            ORDER BY receive_time DESC 
            LIMIT 10
        """)
        
        rows = cursor.fetchall()
        logger.info(f"获取到 {len(rows)} 条样本数据")
        
        for i, row in enumerate(rows):
            sample_id, sample_no, sample_uid, patient_name, receive_time = row
            logger.info(f"样本 {i+1}:")
            logger.info(f"  ID: {sample_id}")
            logger.info(f"  sample_no: {sample_no} (类型: {type(sample_no)})")
            logger.info(f"  sample_uid: {sample_uid} (类型: {type(sample_uid)})")
            logger.info(f"  患者姓名: {patient_name}")
            logger.info(f"  接收时间: {receive_time}")
            logger.info("")
        
        # 检查是否有空的样本编号
        cursor.execute("""
            SELECT COUNT(*) as total,
                   COUNT(CASE WHEN sample_no IS NULL OR sample_no = '' THEN 1 END) as empty_sample_no,
                   COUNT(CASE WHEN sample_uid IS NULL OR sample_uid = '' THEN 1 END) as empty_sample_uid
            FROM lis_samples
        """)
        
        count_row = cursor.fetchone()
        total, empty_sample_no, empty_sample_uid = count_row
        
        logger.info(f"数据统计:")
        logger.info(f"  总样本数: {total}")
        logger.info(f"  空 sample_no: {empty_sample_no}")
        logger.info(f"  空 sample_uid: {empty_sample_uid}")
        
        # 检查样本编号的分布
        cursor.execute("""
            SELECT sample_no, COUNT(*) as count
            FROM lis_samples
            WHERE sample_no IS NOT NULL AND sample_no != ''
            GROUP BY sample_no
            ORDER BY count DESC
            LIMIT 10
        """)
        
        sample_no_distribution = cursor.fetchall()
        logger.info(f"\n样本编号分布 (前10个):")
        for sample_no, count in sample_no_distribution:
            logger.info(f"  {sample_no}: {count} 次")

def debug_database_pagination():
    """调试数据库分页管理器"""
    logger.info("\n=== 调试数据库分页管理器 ===")
    
    db_manager = DatabaseManager()
    db_path = db_manager.db_path
    
    # 创建数据库分页管理器
    pagination_manager = DatabasePaginationManager(db_path, page_size=5)
    
    # 获取第一页数据
    samples, pagination_info = pagination_manager.get_current_page_data()
    
    logger.info(f"分页信息: {pagination_info}")
    logger.info(f"获取到 {len(samples)} 条样本")
    
    for i, sample in enumerate(samples):
        logger.info(f"样本 {i+1}:")
        logger.info(f"  完整数据: {sample}")
        logger.info(f"  sample_no: {sample.get('sample_no', 'NOT_FOUND')}")
        logger.info(f"  sample_uid: {sample.get('sample_uid', 'NOT_FOUND')}")
        logger.info("")

def debug_ui_table_filling():
    """调试UI表格填充逻辑"""
    logger.info("\n=== 调试UI表格填充逻辑 ===")
    
    db_manager = DatabaseManager()
    db_path = db_manager.db_path
    
    # 创建数据库分页管理器
    pagination_manager = DatabasePaginationManager(db_path, page_size=5)
    
    # 获取数据
    samples, pagination_info = pagination_manager.get_current_page_data()
    
    # 模拟UI表格填充逻辑
    for i, sample in enumerate(samples):
        logger.info(f"表格行 {i+1}:")
        
        # 模拟主窗口中的填充逻辑
        sample_id = sample.get('id', '')
        sample_number = sample.get('sample_no', '')
        
        logger.info(f"  样本ID: {sample_id}")
        logger.info(f"  样本编号: {sample_number}")
        logger.info(f"  样本编号类型: {type(sample_number)}")
        logger.info(f"  样本编号是否为空: {sample_number == '' or sample_number is None}")
        
        # 检查其他可能用于显示的字段
        logger.info(f"  sample_uid: {sample.get('sample_uid', '')}")
        logger.info(f"  patient_name: {sample.get('patient_name', '')}")
        logger.info("")

def check_database_schema():
    """检查数据库表结构"""
    logger.info("\n=== 检查数据库表结构 ===")
    
    db_manager = DatabaseManager()
    db_path = db_manager.db_path
    
    import sqlite3
    
    with sqlite3.connect(db_path) as conn:
        cursor = conn.cursor()
        
        # 获取表结构
        cursor.execute("PRAGMA table_info(lis_samples)")
        columns = cursor.fetchall()
        
        logger.info("lis_samples 表结构:")
        for col in columns:
            col_index, col_name, col_type, not_null, default_val, pk = col
            logger.info(f"  {col_name}: {col_type} (NOT NULL: {not_null}, DEFAULT: {default_val}, PK: {pk})")
        
        # 检查索引
        cursor.execute("PRAGMA index_list(lis_samples)")
        indexes = cursor.fetchall()
        
        logger.info(f"\n索引信息:")
        for index in indexes:
            logger.info(f"  {index}")

def main():
    """主函数"""
    logger.info("样本编号显示问题调试程序启动")
    
    # 检查数据库表结构
    check_database_schema()
    
    # 调试样本编号数据
    debug_sample_number_data()
    
    # 调试数据库分页管理器
    debug_database_pagination()
    
    # 调试UI表格填充逻辑
    debug_ui_table_filling()
    
    logger.info("\n调试程序结束")

if __name__ == "__main__":
    main()
